package com.zzy.demo.config.handler;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzy.cms.core.dto.CodeMsg;
import com.zzy.cms.core.dto.Result;
import com.zzy.cms.core.exception.BizException;
import com.zzy.cms.core.exception.GlobalException;

import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result<String> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		log.error("{}", e);
		if (e instanceof GlobalException) {
			GlobalException ex = null;
			try {
				ex = (GlobalException) e;
				return Result.error(ex.getCodeMsg());
			} catch (Exception e1) {
				return Result.error(CodeMsg.COMMON_SERVER_ERROR);
			}
		}else if (e instanceof BizException) {
			BizException ex = null;
			try {
				ex = (BizException) e;
				return Result.error(ex.getCodeMsg());
			} catch (Exception e1) {
				return Result.error(CodeMsg.COMMON_SERVER_ERROR);
			}
		} else {
			return Result.error(CodeMsg.COMMON_SERVER_ERROR);
		}
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
        WebServerFactoryCustomizer<ConfigurableWebServerFactory>  result = new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
                ErrorPage error500Page = new ErrorPage(HttpStatus.NOT_FOUND, "/error/500");
                factory.addErrorPages( error404Page);
                factory.addErrorPages( error500Page);
            }
        };
        return  result;
    }
}